package com.weimob.xh.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

public class QRCodeGenerator {

    public static void main(String[] args) {
        String url = "https://www.baidu.com/?schoolId=123456&gradeCode=01"; // 要生成二维码的链接
        String outputFolder = "./qrcodes"; // 存放二维码的文件夹

        generateAndSaveQRCode(url, outputFolder);
    }

    public static void generateAndSaveQRCode(String url, String outputFolder) {
        Map<String, String> parameters = extractParameters(url);
        String schoolId = parameters.get("schoolId");
        String gradeCode = parameters.get("gradeCode");

        String folderPath = outputFolder + File.separator + schoolId + File.separator + gradeCode;
        String filePath = folderPath + File.separator + "qrcode.png";

        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        generateQRCode(url, filePath);
        System.out.println("二维码已生成至：" + filePath);
    }

    public static void generateQRCode(String text, String filePath) {
        int width = 300;
        int height = 300;
        String format = "png";

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
            Path path = Paths.get(filePath);
            MatrixToImageWriter.writeToPath(bitMatrix, format, path);
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, String> extractParameters(String url) {
        Map<String, String> parameters = new HashMap<>();
        String patternString = "([^?=&]+)(=([^&]*))?";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(url.substring(url.indexOf("?") + 1));

        while (matcher.find()) {
            String key = matcher.group(1);
            String value = matcher.group(3);
            parameters.put(key, value);
        }

        return parameters;
    }
}